#include <iostream>
#include <unistd.h>
#include <pthread.h>
#include <sys/types.h>
#include <unistd.h>
#include <functional>
#include <vector>

using namespace std;
using func_t = function<void()>;

__thread int cnt = 100;

const int thread_num=5;

class ThreadData
{
public:
    ThreadData(const string& _thread_name, uint64_t _create_time, func_t _func)
        : thread_name(_thread_name),create_time(_create_time),func(_func)
    {}

    string thread_name;
    uint64_t create_time;
    func_t func;

};

/* void *Thread_func(void *arg) // 新的线程时在同一个进程之中的
{
    const char *threadname = (const char *)arg;
    while (1)
    {
        cout << "New thread: " << threadname << " pid: " << getpid() << " cnt:" << cnt-- << endl;
        sleep(1);
    }
} */

void Print()
{
    cout<<"线程执行中!"<<endl;
}

void *Thread_func(void *arg) // 新的线程时在同一个进程之中的
{
    int a=10;
    ThreadData *td = static_cast<ThreadData *>(arg);
    while (1)
    {
        cout << "New thread: " << td->thread_name << " create time: " << td->create_time << " cnt:" << cnt-- << endl;
        td->func();
        sleep(1);
        if(td->thread_name == "thread-1"&&cnt==90)
        {
            std::cout << td->thread_name << " 触发了异常!!!!!" << std::endl;   //线程中，只要其中一个线程出现异常，整个线程就会退出
            a/=0;
        }
    }
    //PTHREAD_CANCELED
}


int main()
{
    // int pthread_create(pthread_t *thread, const pthread_attr_t *attr,void *(*start_routine) (void *), void *arg);

  /*   pthread_t tid;
    pthread_create(&tid, nullptr, Thread_func, (void *)"thread_1");
    pthread_create(&tid, nullptr, Thread_func, (void *)"thread_2");
    pthread_create(&tid, nullptr, Thread_func, (void *)"thread_3");
    pthread_create(&tid, nullptr, Thread_func, (void *)"thread_4");
 */
    // ps: Linux 使用线程，需要加入 pthread 库

    // 主线程
    /* while (1)
    {
        cout << "main thread"
             << " pid: " << getpid() << " cnt:" << cnt << endl;
        sleep(1);
    } */


    vector<pthread_t> pthreads;

    for(int i=0;i<thread_num;i++)
    {
        char threadname[64];
        snprintf(threadname, sizeof(threadname), "%s-%lu", "thread", i);
        //线程命名

        pthread_t tid;
        ThreadData *td = new ThreadData(threadname,(uint64_t)time(nullptr),Print);
        pthread_create(&tid,nullptr,Thread_func,td);
        pthreads.push_back(tid);
        cout<<"create pthread,tid: "<<tid<<endl;
        sleep(1);
    }
    while(1)
    {
        sleep(1);
    }

}